import type { Login } from '@/api/model/login'
import type { MenuRouter } from '@/api/model/user'
import { getStorage, removeStorage, setStorage } from '@/utils/cache/storage'
import { defineStore } from 'pinia'
import { login } from '@/api/login'
import router from '@/router/index'
interface InfoState {
  userName: string
  token: string
  expiresTime: number
  refreshToken: string
  tokenTime: number
  routers: string[]
  refreshState: boolean
  user_id: string
  isNew: boolean
  isShowHeader: boolean
  showMenu: boolean
}
const recurseRouters = (
  arr: MenuRouter[],
  routers: string[],
  prefix: string
) => {
  arr.forEach((i: MenuRouter) => {
    const newPrefix = prefix + i.component
    routers.push(newPrefix)
    if (i.children.length > 0) {
      recurseRouters(i.children, routers, newPrefix)
    }
  })
}

export const useInfoStore = defineStore('userinfo', {
  state: (): InfoState => ({
    userName: getStorage('user-name') ?? '',
    token: getStorage('user-token') ?? '',
    expiresTime: parseInt(getStorage('expires-time') ?? '-1'),
    refreshToken: getStorage('refresh-token') ?? '',
    tokenTime: parseInt(getStorage('token-time') ?? '-1'),
    routers: getStorage('routers')?.split(',') ?? [],
    refreshState: false,
    user_id: getStorage('user-id') ?? '',
    isNew: false,
    isShowHeader: Boolean(parseInt(getStorage('is-show-header') ?? '0')),
    showMenu: Boolean(parseInt(getStorage('show-menu') ?? '1'))
  }),
  actions: {
    getUserInfo(info: Login) {
      this.token = info.access_token
      setStorage('user-token', this.token)

      this.userName = info.user_name
      setStorage('user-name', this.userName)

      // 超时时间
      this.expiresTime = info.expires_in * 1000
      setStorage('expires-time', this.expiresTime.toString())
      // refreshToken
      this.refreshToken = info.refresh_token
      setStorage('refresh-token', this.refreshToken)
      // 获取token时间
      this.tokenTime = new Date().getTime()
      setStorage('token-time', this.tokenTime.toString())
      // user_id
      this.user_id = info.user_id
      setStorage('user-id', this.user_id.toString())

      this.isNew = true
    },
    logout() {
      removeStorage('user-token')
      removeStorage('user-name')
      removeStorage('expires-time')
      removeStorage('refresh-token')
      removeStorage('token-time')
      removeStorage('SeniorFilterOptions', false)
      sessionStorage.removeItem('jobPageInit')
      sessionStorage.removeItem('jobOngoingPageInit')
      sessionStorage.removeItem('jobCompletedPageInit')
      sessionStorage.removeItem('auditStrategyPageInit')
      sessionStorage.removeItem('dataAuditPageInit')
      sessionStorage.removeItem('difficultRecheckPageInit')
    },
    // 是否超时
    isOverTime(): boolean {
      const currTime = new Date().getTime()
      const duration = currTime - this.tokenTime
      if (duration > this.expiresTime) return false
      return this.expiresTime - duration < 15 * 60 * 1000
    },
    getRouters(arr: MenuRouter[]) {
      this.routers.length = 0
      recurseRouters(arr, this.routers, '')
      this.routers.push('/imageLabel')
      setStorage('routers', this.routers.join(','))
      this.isNew = false
    },
    canOperate(str: string): boolean {
      return this.routers.includes(str)
    },
    // 刷新token
    async refreshTokenFun() {
      // const flag = this.isOverTime()
      if (this.refreshState) {
        return await new Promise((resolve) => {
          resolve('pending')
        })
      } else {
        this.refreshState = true
        return await new Promise((resolve, reject) => {
          if (this.isOverTime()) {
            login(
              {
                grant_type: 'refresh_token',
                refresh_token: this.refreshToken,
                client_id: 'hmc',
                client_secret: '123456'
              },
              true
            )
              .then((res) => {
                console.log('refresh111111', res)
                if (res != null) {
                  console.log('refresh', res)
                  this.getUserInfo(res as any)
                  this.refreshState = false
                  resolve('success')
                }
              })
              .catch(async (error) => {
                void router.push('/login')
                reject(error)
                this.refreshState = false
              })
          } else {
            resolve('error')
            this.refreshState = false
          }
        })
      }
    },
    setShowHeader(showHeader: boolean) {
      this.isShowHeader = showHeader
      setStorage('is-show-header', String(Number(showHeader)))
    },
    setShowMenu(showMenu: boolean) {
      this.showMenu = showMenu
      setStorage('show-menu', String(Number(showMenu)))
    }
  }
})
